package com.lich.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import com.lich.entity.AppError;
import com.lich.entity.City;
import com.lich.entity.ClientFunction;
import com.lich.entity.Product;
import com.lich.entity.vo.Page;
import com.lich.entity.vo.Result;
import com.lich.service.CityService;
import com.lich.service.ClientFunctionService;
import com.lich.service.ProductService;
import com.lich.util.LocationUtil;
import com.mysql.jdbc.StringUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 
 * 此类描述的是：事件控制器
 * 
 * @author: lining
 * @Time: 2016年9月22日
 */
@Controller
@RequestMapping("/clientfunction")
public class ClientFunctionController {
	@Resource
	CityService cityservice;
	@Resource
	ClientFunctionService clientFunctionService;
	@Resource
	ProductService productService;

	/**
	 * 
	 * 此方法描述的是：添加发生的事件
	 * 
	 * @author: lining
	 * @Time: 2016年9月22日
	 * @param clients
	 * @param res
	 * @throws IOException
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public void add(@RequestBody List<ClientFunction> clientFunctions, HttpServletRequest req, HttpServletResponse res) throws IOException {

		getLocationAddress(clientFunctions, req.getHeader("logAndLat"));

		PrintWriter writer = res.getWriter();
		JSONArray arr = new JSONArray();
		JSONObject obj = new JSONObject();

		// TODO 数据过滤

		Result<ClientFunction> result = new Result<ClientFunction>();
		try {
			filterUUid(clientFunctions);
			if (clientFunctions.size() > 0 && clientFunctionService.addList(clientFunctions) > 0) {
				result.setSuccess(true);
				result.setMessage("添加事件记录成功");

				obj.put("results", "sucess");
				arr.add(obj);

			} else {
				result.setSuccess(true);
				result.setMessage("添加事件记录失败 ");

				obj.put("results", "fail");
				arr.add(obj);
			}
		} catch (Exception e) {
			arr.clear();
		} finally {

			writer.println(arr.toString());
			writer.flush();
			writer.close();
		}

	}

	/**
	 * 过滤掉不存在的UUID
	 * 
	 * @param clients
	 */
	private void filterUUid(List<ClientFunction> clients) {
		List<Product> products = productService.getAll();
		// TODO 数据过滤
		Iterator<ClientFunction> iterator = clients.iterator();
		while (iterator.hasNext()) {
			ClientFunction clientFunction = iterator.next();
			String productID = clientFunction.getProductId();
			if (!StringUtils.isNullOrEmpty(productID)) {
				boolean hasProductId = false;
				for (Product product : products) {
					if (product.getUuid().equals(productID)) {// 判断是否存在UUID
						hasProductId = true;
						break;
					}
				}
				if (!hasProductId) {// 不存在的UUID过滤掉
					iterator.remove();
				}
			} else {
				iterator.remove();
			}
		}
	}

	/**
	 * 
	 * @param request
	 * @param clientFunction
	 * @return
	 */
	@RequestMapping(value = "/functionCall", method = RequestMethod.POST)
	public ModelAndView saveClientFunction(HttpServletRequest request, ClientFunction clientFunction) {
		Result<Page<AppError>> result = new Result<>();

		if (clientFunction == null) {
			result.setSuccess(false);
			result.setMessage("参数错误！");
			return new ModelAndView(new MappingJackson2JsonView(), "result", result);
		}
		if (clientFunction.getFunctionTime() == null) {
			result.setSuccess(false);
			result.setMessage("functionTime 不能为空！");
			return new ModelAndView(new MappingJackson2JsonView(), "result", result);

		}
		if (clientFunction.getFunctionId() == null) {
			result.setSuccess(false);
			result.setMessage("functionId 不能为空！");
			return new ModelAndView(new MappingJackson2JsonView(), "result", result);

		}
		if (clientFunction.getAppVersion() == null) {
			result.setSuccess(false);
			result.setMessage("appVersion 不能为空！");
			return new ModelAndView(new MappingJackson2JsonView(), "result", result);

		}
		if (clientFunction.getProductId() == null) {
			result.setSuccess(false);
			result.setMessage("productId 不能为空！");
			return new ModelAndView(new MappingJackson2JsonView(), "result", result);

		}
		if (clientFunction.getUsername() == null) {
			result.setSuccess(false);
			result.setMessage("userName 不能为空！");
			return new ModelAndView(new MappingJackson2JsonView(), "result", result);

		}
		try {
			clientFunctionService.save(clientFunction);
			result.setSuccess(true);
			result.setMessage("添加成功！");
			return new ModelAndView(new MappingJackson2JsonView(), "result", result);
		} catch (Exception e) {
			// TODO: handle exception
			result.setSuccess(false);
			result.setMessage("系统异常！");
			return new ModelAndView(new MappingJackson2JsonView(), "result", result);
		}

	}

	/**
	 * 
	 * 此方法描述的是：根据app传递过来的经纬度得到地址
	 * 
	 * @author: lining
	 * @Time: 2016年9月28日
	 * @param clients
	 */
	private void getLocationAddress(List<ClientFunction> clients, String logAndLat) {
		for (ClientFunction client : clients) {
			String cityname = LocationUtil.getCityName(logAndLat);
			City city = null;
			if (cityname != null) {
				city = cityservice.getCityId(cityname);
			}
			if (city != null) {
				client.setCityId(city.getId());
				client.setProvincialId(city.getProvincialId());
			}
		}
	}

}
